/* login.js */
import IMService from '../../static/lib/imservice.js';
const app = getApp()
Page({
	data: {
		username:"",
		password:"",
		showError:false,
	},
	login: function(e) {
		var username = e.detail.value.username;
		var password = e.detail.value.password;
		if (username.trim() != "" && password.trim() != "") {
			// 将IMService定义为全局变量
			let service = app.globalData.imService = new IMService(wx.im);
			let loginResult = service.login(username, password);
			if (loginResult) {
				// 连接IM
				service.connectIM();

				//订阅群消息
				this.subscribeGroupMessage();

				// 页面跳转
				wx.switchTab({
					url:'../conversations/conversations'
				})
				return;
			}
		}
		this.setData({
			showError:true
		});
	},
	subscribeGroupMessage () {
		let service = app.globalData.imService;
		let groups = service.groups;
		let groupIds = Object.keys(groups);
		wx.im.subscribeGroup(groupIds)
			.then(() => {
				console.log('订阅群消息成功')
			})
			.catch(error => {
				console.log('订阅群消息失败', error);
			})
	}
})